import * as React from "react"
import { getServerSession } from "next-auth/next"
import { authOptions } from "@/app/api/auth/[...nextauth]/route"
import { redirect } from "next/navigation"
import { Shell } from "@/components/shell"
import { getContractForVendorReview } from "@/lib/general-contracts/service"
import { VendorContractReviewClient, type VendorContractReviewClientProps } from "./vendor-contract-review-client"

interface VendorContractReviewPageProps {
  params: Promise<{ contractId: string }>
}

export default async function VendorContractReviewPage(props: VendorContractReviewPageProps) {
  const resolvedParams = await props.params
  const contractId = parseInt(resolvedParams.contractId)

  if (isNaN(contractId)) {
    redirect('/partners')
  }

  // 세션에서 벤더 정보 가져오기
  const session = await getServerSession(authOptions)
  if (!session?.user?.companyId) {
    return (
      <div className="flex h-full items-center justify-center p-6">
        정상적인 벤더에 소속된 계정이 아닙니다.
      </div>
    )
  }

  const vendorId = session.user.companyId

  try {
    // 협력업체용 계약 정보 조회
    const contract = await getContractForVendorReview(contractId, vendorId)

    return (
      <Shell className="gap-2">
        <VendorContractReviewClient 
          contract={{
            ...contract,
            name: contract.name || '',
          } as VendorContractReviewClientProps['contract']}
          vendorId={vendorId}
        />
      </Shell>
    )
  } catch (error) {
    console.error('계약 정보 조회 오류:', error)
    return (
      <div className="flex h-full items-center justify-center p-6">
        <div className="text-center space-y-2">
          <p className="text-destructive">계약 정보를 불러올 수 없습니다.</p>
          <p className="text-muted-foreground text-sm">
            {error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.'}
          </p>
        </div>
      </div>
    )
  }
}

